package thread;

/**
 * 死锁
 * 当两个线程在持有各自对象的同时都在等待对方释放锁时就会出现一种"僵持"状态,这个现象称为死锁
 */
public class DeadLockDemo {
    private static Object chopsticks = new Object();//筷子
    private static Object spoon = new Object();//勺子

    public static void main(String[] args) {
        Thread np = new Thread(() -> {
            try {
                System.out.println("北方人开始吃饭");
                System.out.println("北方人去拿筷子...");
                synchronized (chopsticks) {
                    System.out.println("北方人拿起筷子开始吃饭");
                    Thread.sleep(5000);
                    System.out.println("北方人吃完饭去拿勺子");
                    synchronized (spoon) {
                        System.out.println("北方人拿起勺子喝汤");
                        Thread.sleep(5000);
                    }
                    System.out.println("北方人放下勺子...");
                }
                System.out.println("北方人放下筷子  吃饭完毕!");
            } catch (Exception e) {
            }
        });
        Thread sp = new Thread(() -> {
            try {
                System.out.println("南方人开始吃饭");
                System.out.println("南方人去拿勺子...");
                synchronized (spoon) {
                    System.out.println("南方人拿起勺子开始喝汤");
                    Thread.sleep(5000);
                    System.out.println("南方人喝完汤去拿筷子");
                    synchronized (chopsticks) {
                        System.out.println("南方人拿起筷子吃饭");
                        Thread.sleep(5000);
                    }
                    System.out.println("南方人放下筷子...");
                }
                System.out.println("南方人放下勺子  吃饭完毕!");
            } catch (Exception e) {
            }
        });
        np.start();
        sp.start();
    }
}
